package com.easy.util;

import javax.servlet.http.HttpSession;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;

public class CaptchaUtil {

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
    private static final int WIDTH = 130;
    private static final int HEIGHT = 48;

    // 生成验证码并保存到session
    public static void generateCaptcha(HttpSession session, OutputStream outputStream) throws IOException {
        // 加载背景图片
        BufferedImage backgroundImage = ImageIO.read(CaptchaUtil.class.getResourceAsStream("/image/2.jpg"));

        // 创建图像对象
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) image.getGraphics();

        // 绘制背景图片
        g.drawImage(backgroundImage, 0, 0, WIDTH, HEIGHT, null);

        // 生成验证码a
        String captchaText = generateRandomString(4);
        session.setAttribute("captcha", captchaText);

        // 设置字体
        g.setFont(new Font("Arial", Font.BOLD, 30));

        // 绘制每个字符
        Random random = new Random();
        for (int i = 0; i < captchaText.length(); i++) {
            // 随机颜色
            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));

            // 随机字体大小和风格
            int fontSize = 24 + random.nextInt(8);
            g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, fontSize));

            // 随机旋转角度
            AffineTransform originalTransform = g.getTransform();
            g.rotate(Math.toRadians(random.nextInt(45) - 22.5), (WIDTH / 4) * (i + 0.5), HEIGHT / 2);

            // 随机字符位置
            int x = (WIDTH / 4) * i + 10 + random.nextInt(5);
            int y = HEIGHT / 2 + 10 + random.nextInt(5);

            // 绘制字符
            g.drawString(String.valueOf(captchaText.charAt(i)), x, y);

            // 恢复原始的变换
            g.setTransform(originalTransform);
        }

        // 释放图形对象
        g.dispose();

        // 将验证码图片写入输出流
        ImageIO.write(image, "jpg", outputStream);
    }

    // 生成随机字符串
    private static String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder(length);
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
        }
        return sb.toString();
    }

    // 验证用户输入的验证码
    public static boolean verifyCaptcha(HttpSession session, String userCaptcha) {
        // 从 session 中获取存储的验证码
        String sessionCaptcha = (String) session.getAttribute("captcha");
        // 验证用户输入的验证码是否匹配
        return sessionCaptcha != null && sessionCaptcha.equalsIgnoreCase(userCaptcha);
    }
}
